package com.yihu.wlyy.web.patient.health;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yihu.wlyy.entity.Medicines;
import com.yihu.wlyy.entity.patient.PatientHealthRecordDiet;
import com.yihu.wlyy.entity.patient.PatientHealthRecordMedication;
import com.yihu.wlyy.entity.patient.PatientHealthRecordSports;
import com.yihu.wlyy.entity.health_guide.Sports;
import com.yihu.wlyy.entity.health_guide.SportsType;
import com.yihu.wlyy.service.app.health.PatientHealthRecordService;
import com.yihu.wlyy.service.app.medicines.MedicinesService;
import com.yihu.wlyy.service.app.sports.SportsService;
import com.yihu.wlyy.util.CommonUtil;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.web.WeixinBaseController;

/**
 * 健康记录控制类
 * @author George
 *
 */
@Controller
@RequestMapping(value = "/patient/health_record")
public class PatientHealthRecordController extends WeixinBaseController {

	@Autowired
	private SportsService sportsService;

	@Autowired
	private MedicinesService medicinesService;

	@Autowired
	private PatientHealthRecordService patientHealthRecordService;

	/**
	 * 运动强度查询接口
	 * @return
	 */
	@RequestMapping(value = "sports_type")
	@ResponseBody
	public String sportsType() {
		try {
			JSONArray array = new JSONArray();
			List<SportsType> list = sportsService.finsAllSportsType();
			if (list != null) {
				for (SportsType temp : list) {
					if (temp == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					json.put("code", temp.getCode());
					json.put("name", temp.getName());
					array.put(json);
				}
			}
			return write(200, "查询成功", "list", array);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败");
		}
	}

	/**
	 * 运动类型查询接口
	 * @return
	 */
	@RequestMapping(value = "sports")
	@ResponseBody
	public String sports() {
		try {
			JSONArray array = new JSONArray();
			List<Sports> list = sportsService.finsAllSports();
			if (list != null) {
				for (Sports temp : list) {
					if (temp == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					json.put("code", temp.getCode());
					json.put("name", temp.getName());
					array.put(json);
				}
			}
			return write(200, "查询成功", "list", array);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败");
		}
	}

	/**
	 * 查询药品列表
	 * @return
	 */
	@RequestMapping(value = "medicines")
	@ResponseBody
	public String medicines() {
		try {
			JSONArray array = new JSONArray();
			List<Medicines> list = medicinesService.findAllMedicines(1);
			if (list != null) {
				for (Medicines temp : list) {
					if (temp == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					json.put("code", temp.getCode());
					json.put("name", temp.getName());
					array.put(json);
				}
			}
			return write(200, "查询成功", "list", array);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败");
		}
	}

	/**
	 * 添加运动记录
	 * @param record_date 记录时间
	 * @param sportsTime 运动时长（分）
	 * @param sportsType 运动强度标识
	 * @param sports 运动类型标识
	 * @return
	 */
	@RequestMapping(value = "add_sports")
	@ResponseBody
	public String addSports(String record_date, double sportsTime, String sportsType, String sports) {
		try {
			PatientHealthRecordSports record = new PatientHealthRecordSports();
			record.setDel("1");
			record.setCzrq(new Date());
			record.setPatient(getUID());
			record.setRecordDate(DateUtil.strToDateShort(record_date));
			record.setSortDate(DateUtil.strToDateAppendNowTime(record_date, DateUtil.YYYY_MM_DD_HH_MM_SS));
			record.setSportsTime(sportsTime);
			if (patientHealthRecordService.addSports(record, sportsType, sports) != null) {
				return success("保存成功");
			} else {
				return error(-1, "保存失败");
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "保存失败");
		}
	}

	/**
	 * 添加用药记录
	 * @param record_date 记录时间
	 * @param medicines 药品标识
	 * @param medicines_name 药品名称
	 * @return
	 */
	@RequestMapping(value = "add_medication")
	@ResponseBody
	public String addMedication(String record_date, String medicines, String medicines_name) {
		try {
			PatientHealthRecordMedication record = new PatientHealthRecordMedication();
			record.setDel("1");
			record.setCzrq(new Date());
			record.setPatient(getUID());
			record.setRecordDate(DateUtil.strToDateShort(record_date));
			record.setSortDate(DateUtil.strToDateAppendNowTime(record_date, DateUtil.YYYY_MM_DD_HH_MM_SS));
			record.setMedicines(medicines);
			record.setMedicinesName(medicines_name);
			if (patientHealthRecordService.addMedication(record) != null) {
				return success("保存成功");
			} else {
				return error(-1, "保存失败");
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "保存失败");
		}
	}

	/**
	 * 添加饮食记录接口
	 * @param record_date 记录时间
	 * @param content 饮食内容
	 * @param images 图片HTTP地址，多图以逗号分隔
	 * @return
	 */
	@RequestMapping(value = "add_diet")
	@ResponseBody
	public String add(String record_date, String content, @RequestParam(required = false) String images) {
		try {
			PatientHealthRecordDiet record = new PatientHealthRecordDiet();
			record.setDel("1");
			record.setCzrq(new Date());
			record.setPatient(getUID());
			record.setRecordDate(DateUtil.strToDateShort(record_date));
			record.setSortDate(DateUtil.strToDateAppendNowTime(record_date, DateUtil.YYYY_MM_DD_HH_MM_SS));
			record.setContent(content);
			// 从微信服务器获取图片
			if (StringUtils.isEmpty(images)) {
				images = fetchWxImages();
			}
			if (StringUtils.isNotEmpty(images)) {
				images = CommonUtil.copyTempImage(images);
			}
			record.setImages(images);
			if (patientHealthRecordService.addDiet(record) != null) {
				return success("保存成功");
			} else {
				return error(-1, "保存失败");
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "保存失败");
		}
	}

	/**
	 * 最近填写的运动、用药、饮食内容
	 * @return
	 */
	@RequestMapping(value = "recent")
	@ResponseBody
	public String recent() {
		try {
			JSONObject json = patientHealthRecordService.findRecentByPatient(getUID());
			if (json != null) {
				return write(200, "查询成功", "data", json);
			} else {
				return error(-1, "查询失败");
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败");
		}
	}

	/**
	 * 运动记录查询接口
	 * @param pagesize 分页大小
	 * @return
	 */
	@RequestMapping(value = "list_sports")
	@ResponseBody
	public String sports(String start,String end,int page, int pagesize) {
		try {
			Page<PatientHealthRecordSports> data = patientHealthRecordService.findSportsByPatientPage(getUID(), start,end,page, pagesize);
			if (data != null) {
				JSONArray array = new JSONArray();
				for (PatientHealthRecordSports record : data) {
					if (record == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					json.put("id", record.getId());
					// 设置记录标识
					json.put("code", record.getCode());
					// 设置记录日期
					json.put("record_date", DateUtil.dateToStrShort(record.getRecordDate()));
					json.put("sortDate", DateUtil.dateToStrLong(record.getSortDate()));
					// 设置运动时长（分钟）
					json.put("sports_time", record.getSportsTime());
					// 设置运动强度
					json.put("sports_type", record.getSportsTypeName());
					// 设置运动类型
					json.put("sports", record.getSportsName());
					array.put(json);
				}
				return write(200, "查询成功", "list", array);
			} else {
				return error(-1, "查询失败");
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败");
		}
	}

	/**
	 * 用药记录查询接口
	 * @param pagesize 分页大小
	 * @return
	 */
	@RequestMapping(value = "list_medication")
	@ResponseBody
	public String medication(String start,String end,int page, int pagesize) {
		try {
			Page<PatientHealthRecordMedication> data = patientHealthRecordService.findMedicalByPatientPage(getUID(), start, end, page, pagesize);
			if (data != null) {
				JSONArray array = new JSONArray();
				for (PatientHealthRecordMedication record : data) {
					if (record == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					json.put("id", record.getId());
					// 设置记录标识
					json.put("code", record.getCode());
					// 设置记录日期
					json.put("record_date", DateUtil.dateToStrShort(record.getRecordDate()));
					json.put("sortDate", DateUtil.dateToStrLong(record.getSortDate()));
					// 药品名称
					json.put("medicines", record.getMedicinesName());
					array.put(json);
				}
				return write(200, "查询成功", "list", array);
			} else {
				return error(-1, "查询失败");
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败");
		}
	}

	/**
	 * 饮食记录查询接口
	 * @param pagesize 分页大小
	 * @return
	 */
	@RequestMapping(value = "list_diet")
	@ResponseBody
	public String diet(String start,String end,int page,int pagesize) {
		try {
			Page<PatientHealthRecordDiet> data = patientHealthRecordService.findDietByPatientPage(getUID(),start,end,page, pagesize);
			if (data != null) {
				JSONArray array = new JSONArray();
				for (PatientHealthRecordDiet record : data) {
					if (record == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					json.put("id", record.getId());
					// 设置记录标识
					json.put("code", record.getCode());
					// 设置记录日期
					json.put("record_date", DateUtil.dateToStrShort(record.getRecordDate()));
					json.put("sortDate", DateUtil.dateToStrLong(record.getSortDate()));
					// 设置饮食内容
					json.put("content", record.getContent());
					// 设置图片URL,多图以逗号分隔
					json.put("images", record.getImages());
					array.put(json);
				}
				return write(200, "查询成功", "list", array);
			} else {
				return error(-1, "查询失败");
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败");
		}
	}

}
